package org.jeecg.modules.demo.seal.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.evaluate.entity.Evaluate;
import org.jeecg.modules.demo.partner.entity.Partner;
import org.jeecg.modules.demo.seal.entity.*;
import org.jeecg.modules.demo.seal.service.ICarService;
import org.jeecg.modules.demo.seal.service.ISealService;
import org.jeecg.modules.demo.seal.util.DateUtils;
import org.jeecg.modules.demo.utils.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Api(tags="Seal")
@RestController
@RequestMapping("/Seal/Seal")
@Slf4j
public class CarSealController {

    @Autowired
    private ISealService sealService;
    @Autowired
    private ICarService carService;

    /**
     * 分页列表查询 封存车辆
     *
     * @param car
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "CarSeal-分页列表查询 封存车辆")
    @ApiOperation(value="CarSeal-分页列表查询 封存车辆", notes="CarSeal-分页列表查询 封存车辆")
    @GetMapping(value = "/list")
    public Result<IPage<CarSeal>> queryPageList(Car car,
                                                @RequestParam(name="orgCode", required = false) String orgCode,
                                                @RequestParam(name="userid", defaultValue="1") String userid,
                                                @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                HttpServletRequest req) throws ParseException {

        SealTime sealTime = sealService.getStartTime();
        Date currentTime = new Date();
        int result = currentTime.compareTo(sealTime.getEndTime());//比对当前时间与封存结束时间
        if(result > 0){//如果当前时间晚于封存结束时间
            sealTime.setStartTime(currentTime);//设置封存开始时间为当前时间

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(currentTime);
            calendar.add(Calendar.DATE, 1); // 在日期上加一天
            sealTime.setEndTime(calendar.getTime());//设置封存结束时间为当前时间+1天
        }
        String loginOrgCode = sealService.getOrgCode(userid);//部门编号

        if(orgCode == null || "".equals(orgCode)){
            orgCode = loginOrgCode;
        }else if(!orgCode.contains(loginOrgCode)){
            orgCode = loginOrgCode;
        }

        if(orgCode == null){
            orgCode = "";
        }

        Long orgId = carService.getOrgId(orgCode);//物研部门id
        List<Long> orgIdList = carService.getOrgIds(orgCode);//所有下属部门
        orgIdList.add(orgId);

        QueryWrapper<Car> queryWrapper = QueryGenerator.initQueryWrapper(car, req.getParameterMap());
        queryWrapper.eq("if_delete",0);
        queryWrapper.in("org_id",orgIdList);

        Page<Car> page = new Page<Car>(pageNo, pageSize);
        List<Car> list = carService.list(page, queryWrapper);


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<CarSeal> carSealList = new ArrayList<>();//根据组织查询车辆
        for(Car carInfo : list){

            if(carInfo.getBrandModelId() != null){
                CarBrandModel carBrandModel = carService.getBrandModel(carInfo.getBrandModelId());
                if(carBrandModel != null){
                    carInfo.setBrand(carBrandModel.getBrand());// 品牌
                    carInfo.setModel(carBrandModel.getModel());// 车型
                }
            }

            Seal seal = sealService.getByCarId(carInfo.getCarId(), sealTime.getStartTime(), sealTime.getEndTime());

            CarSeal carSeal = new CarSeal();
            if(seal != null){
                BeanUtils.copyProperties(seal,carSeal);
            }
            BeanUtils.copyProperties(carInfo,carSeal);


            String departName = carService.getDepartName(carInfo.getOrgId());
            carSeal.setDepartName(departName);

            String st = "";
            if(carSeal.getSealTime() == null){
                st = sdf.format(new Date());
            }else {
                st = sdf.format(carSeal.getSealTime());
            }
            int i = 0;
            try{
                i = DateUtils.timeCompare(st,sdf.format(sealTime.getStartTime()));
            }catch (Exception e){}

            if(i == 1 && carSeal.getSealStatus() == 1){
                carSeal.setIsdelay(1);
            }else {
                carSeal.setIsdelay(0);
            }

            carSealList.add(carSeal);
        }

        Page<CarSeal> carSealpage = new Page<CarSeal>(pageNo, pageSize);
        carSealpage.setTotal(page.getTotal());
        IPage<CarSeal> pageList = carSealpage.setRecords(carSealList);
        return Result.OK(pageList);
    }


    /**
     * 查询所有组织机构
     *
     * @param orgName
     * @return
     */
    @AutoLog(value = "authOrg-所有组织机构查询 封存车辆")
    @ApiOperation(value="authOrg-所有组织机构查询 封存车辆", notes="authOrg-所有组织机构查询 封存车辆")
    @GetMapping(value = "/getOrg")
    public Result<List<authOrg>> getOrg(@RequestParam(name="orgName", required = false) String orgName){
        if(orgName == null){
            orgName = "";
        }

        List<authOrg> authOrgList = carService.getOrg(orgName);

        return Result.OK(authOrgList);
    }


    /**
     * 分页列表查询 封存车辆
     *
     * @param car
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "CarSeal-分页列表查询 封存车辆")
    @ApiOperation(value="CarSeal-分页列表查询 封存车辆", notes="CarSeal-分页列表查询 封存车辆")
    @GetMapping(value = "/listD")
    public Result<IPage<CarSeal>> queryPageListD(Car car,
                                                 @RequestParam(name="orgCode", required = false) String orgCode,
                                                @RequestParam(name="userid", defaultValue="1") String userid,
                                                @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                HttpServletRequest req) throws ParseException {

        SealTime sealTime = sealService.getStartTime();

        if(orgCode == null || "".equals(orgCode)){
            orgCode = sealService.getOrgCode(userid);//部门编号
        }

        if(orgCode == null){
            orgCode = "";
        }

        Long orgId = carService.getOrgId(orgCode);//物研部门id

        QueryWrapper<Car> queryWrapper = QueryGenerator.initQueryWrapper(car, req.getParameterMap());
        queryWrapper.eq("if_delete",0);
        queryWrapper.eq("org_id",orgId);


        Page<Car> page = new Page<Car>(pageNo, pageSize);
        List<Car> list = carService.list(page, queryWrapper);


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<CarSeal> carSealList = new ArrayList<>();
        for(Car carInfo : list){

            if(carInfo.getBrandModelId() != null){
                CarBrandModel carBrandModel = carService.getBrandModel(carInfo.getBrandModelId());
                if(carBrandModel != null){
                    carInfo.setBrand(carBrandModel.getBrand());// 品牌
                    carInfo.setModel(carBrandModel.getModel());// 车型
                }
            }


            Seal seal = sealService.getByCarId(carInfo.getCarId(), sealTime.getStartTime(), sealTime.getEndTime());

            CarSeal carSeal = new CarSeal();
            if(seal != null){
                BeanUtils.copyProperties(seal,carSeal);
            }
            BeanUtils.copyProperties(carInfo,carSeal);


            String departName = carService.getDepartName(carInfo.getOrgId());
            carSeal.setDepartName(departName);

            String st = "";
            if(carSeal.getSealTime() == null){
                st = sdf.format(new Date());
            }else {
                st = sdf.format(carSeal.getSealTime());
            }
            int i = 0;
            try{

                i = DateUtils.timeCompare(st,sdf.format(sealTime.getStartTime()));
            }catch (Exception e){}
            if(i == 1 && carSeal.getSealStatus() == 1){
                carSeal.setIsdelay(1);
            }else {
                carSeal.setIsdelay(0);
            }

            carSealList.add(carSeal);
        }

        Page<CarSeal> carSealpage = new Page<CarSeal>(pageNo, pageSize);
        carSealpage.setTotal(page.getTotal());
        IPage<CarSeal> pageList = carSealpage.setRecords(carSealList);
        return Result.OK(pageList);

    }



    /**
     *   添加
     *
     * @param seal
     * @return
     */
    @AutoLog(value = "Seal-添加")
    @ApiOperation(value="Seal-添加", notes="Seal-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody Seal seal) throws ParseException {

        SealTime sealTime = sealService.getStartTime();
        String currentTime =DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if(seal.getSealStatus() == 0){
            seal.setSealTime(null);
        }else {
            if(seal.getSealTime() == null){
                seal.setSealTime(new Date());
            }
        }

        seal.setUnblockTime(sealTime.getEndTime());

        sealService.save(seal);
        return Result.OK("添加成功！");
    }

    /**
     *  编辑
     *
     * @param seal
     * @return
     */
    @AutoLog(value = "Seal-编辑")
    @ApiOperation(value="Seal-编辑", notes="Seal-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result<String> edit(@RequestBody Seal seal) throws ParseException {


        SealTime sealTime = sealService.getStartTime();

//        if(seal.getSealStatus() == 0){
//            seal.setSealTime(null);
//        }else {
//            if(seal.getSealTime() == null){
//                seal.setSealTime(new Date());
//            }
//        }
        if(seal.getSealTime() == null){
                seal.setSealTime(new Date());
            }

        seal.setUnblockTime(sealTime.getEndTime());
        sealService.updateSealById(seal);
        sealService.updateById(seal);
        return Result.OK("编辑成功!");
    }

    /**
     *  解封
     *
     * @param id
     * @return
     */
    @AutoLog(value = "Seal-解封")
    @ApiOperation(value="Seal-解封", notes="Seal-解封")
    @GetMapping(value = "/unblock")
    public Result<String> unblock(@RequestParam(name="id") String id) {
        SealTime sealTime = sealService.getStartTime();

        String time =DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss");
        sealService.unblock(id,time);
        return Result.OK("编辑成功!");
    }


    /**
     * 分页列表查询 规定封存时间
     *
     * @return
     */
    @AutoLog(value = "SealTime-规定封存时间")
    @ApiOperation(value="SealTime-规定封存时间", notes="SealTime-规定封存时间")
    @GetMapping(value = "/querySealTime")
    public Result<SealTime> querySealTime() {

        SealTime sealTime = sealService.getSealTime();

        return Result.OK(sealTime);

    }

    /**
     *   修改 规定封存时间
     * @param sealTime
     * @return
     */
    @AutoLog(value = "SealTime-修改")
    @ApiOperation(value="SealTime-修改", notes="SealTime-修改")
    @PostMapping(value = "/editSealTime")
    public Result<String> editSealTime(@RequestBody SealTime sealTime) {




        sealService.updataSealTime(sealTime);
        return Result.OK("修改成功！");
    }
}
